package org.example.volunteerend.interceptor;

import org.example.volunteerend.utils.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;
    private final JdbcTemplate jdbcTemplate;

    public JwtInterceptor(JwtUtil jwtUtil, JdbcTemplate jdbcTemplate) {
        this.jwtUtil = jwtUtil;
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        
        // 对在WebMvcConfig中已经排除的路径再次进行确认
        if (requestURI.equals("/api/users/register") || 
            requestURI.equals("/api/users/login") ||
            requestURI.startsWith("/api/project-categories")) {
            return true;
        }
        
        // 仅对项目列表和详情的GET请求放行
        if ((requestURI.equals("/api/projects") || 
             requestURI.matches("/api/projects/\\d+")) && 
            "GET".equals(method)) {
            return true;
        }

        // 特别检查项目报名相关接口
        if (requestURI.contains("/register")) {
            System.out.println("验证项目报名接口: " + requestURI + ", 方法: " + method);
        }

        // 打印请求头信息，帮助调试
        System.out.println("Request URI: " + requestURI);
        System.out.println("Method: " + method);
        System.out.println("Authorization: " + request.getHeader("Authorization"));
        System.out.println("token: " + request.getHeader("token"));

        // 获取token，同时支持token和Authorization请求头
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            token = request.getHeader("Authorization");
            // 如果是Bearer token格式，去掉Bearer前缀
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null || token.isEmpty()) {
            System.out.println("未提供token");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                System.out.println("token验证失败");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }

            // 将用户ID存入request属性中
            Integer userId = jwtUtil.getUserIdFromToken(token);
            System.out.println("Validated userId from token: " + userId);
            request.setAttribute("userId", userId);
            
            // 查询用户是否是管理员并设置到request属性中
            try {
                String sql = "SELECT is_admin FROM users WHERE user_id = ?";
                Boolean isAdmin = jdbcTemplate.queryForObject(sql, Boolean.class, userId);
                System.out.println("User " + userId + " isAdmin: " + isAdmin);
                request.setAttribute("isAdmin", isAdmin);
            } catch (Exception e) {
                System.out.println("Error checking admin status: " + e.getMessage());
                request.setAttribute("isAdmin", false);
            }
            
            return true;
        } catch (Exception e) {
            System.out.println("Token validation error: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }
} 